<template>
  <div>
    <el-dialog
      :visible.sync="visible"
      :title="questionInfoNow.type ? '编辑问题' : '添加问题'"
      width="80%"
      :before-close="handleClose"
    >
      <!-- 问题表单 -->
      <el-form
        :model="questionAddForm"
        :rules="questionAddFormRules"
        ref="questionAddFormRef"
        label-width="90px"
        label-position="left"
      >
        <el-form-item label="问题分类" prop="question_class">
          <el-select
            v-model="questionAddForm.question_class"
            placeholder="请选择问题分类"
            filterable
            clearable
          >
            <el-option
              v-for="item in classData"
              :key="item.id"
              :label="item.name"
              :value="
                typeof questionAddForm.question_class == 'string'
                  ? item.id + ''
                  : item.id
              "
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题题型" prop="type">
          <el-radio
            v-model="questionAddForm.type"
            :label="typeof questionAddForm.type == 'string' ? '1' : 1"
            >单选题</el-radio
          >
          <el-radio
            v-model="questionAddForm.type"
            :label="typeof questionAddForm.type == 'string' ? '2' : 2"
            >多选题</el-radio
          >
          <el-radio
            v-model="questionAddForm.type"
            :label="typeof questionAddForm.type == 'string' ? '3' : 3"
            >问答题</el-radio
          >
        </el-form-item>
        <el-form-item label="问题标题" prop="title">
          <el-input
            v-model="questionAddForm.title"
            placeholder="请输入问题标题，例如：您的爱宠昵称？"
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="填写内容"
          prop="tips_content"
          v-show="questionAddForm.type == 3"
        >
          <el-input
            v-model="questionAddForm.tips_content"
            placeholder="请输入填写内容提示，例如：您的爱宠叫什么？"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="内容限制"
          prop="content_limit"
          v-show="questionAddForm.type == 3"
          :rules="
            questionAddForm.type == 3
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-select
            v-model="questionAddForm.content_limit"
            placeholder="请选择填写内容限制"
            filterable
            clearable
          >
            <el-option
              key="0"
              label="不限"
              :value="
                typeof questionAddForm.content_limit == 'string' ? '0' : 0
              "
            >
            </el-option>
            <el-option
              key="1"
              label="文本"
              :value="
                typeof questionAddForm.content_limit == 'string' ? '1' : 1
              "
            >
            </el-option>
            <el-option
              key="2"
              label="数字"
              :value="
                typeof questionAddForm.content_limit == 'string' ? '2' : 2
              "
            >
            </el-option>
            <el-option
              key="3"
              label="日期（yyyy-mm-dd）"
              :value="
                typeof questionAddForm.content_limit == 'string' ? '3' : 3
              "
            ></el-option>
            <el-option
              key="4"
              label="手机号码"
              :value="
                typeof questionAddForm.content_limit == 'string' ? '4' : 4
              "
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="字数限制"
          v-show="questionAddForm.type == 3"
          required
        >
          <el-col :span="2">
            <el-form-item prop="word_limit">
              <el-switch
                v-model="questionAddForm.word_limit"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="20" v-show="questionAddForm.word_limit">
            <el-form-item
              prop="word_limit_num"
              :rules="
                questionAddForm.type == 3
                  ? [{ required: true, message: '请输入', trigger: 'blur' }]
                  : []
              "
            >
              <span>字数限制在</span>
              <el-input-number
                size="mini"
                v-model="questionAddForm.word_limit_num"
                controls-position="right"
                style="width: 80px"
              ></el-input-number>
              <span>字以内</span>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item
          label="选项内容"
          prop="option_data"
          v-show="questionAddForm.type != 3"
          :rules="
            questionAddForm.type != 3
              ? [{ required: true, message: '请添加选项内容' }]
              : []
          "
        >
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="12">
              <el-link
                icon="el-icon-circle-plus-outline"
                type="primary"
                :underline="false"
                @click="addSingleOption"
                >增加单个选项</el-link
              >
              &nbsp;
              <el-link
                icon="el-icon-circle-plus-outline"
                type="primary"
                :underline="false"
                @click="addPackOption"
                >增加选项填空</el-link
              >
            </el-col>
            <el-col :span="12" style="text-align: right"
              ><span>选项图片尺寸：177*374，小于1M，支持png格式</span></el-col
            >
          </el-row>
          <el-row>
            <el-form
              ref="optionFormRef"
              :model="optionForm"
              :rules="optionFormRules"
              style="width: 100%; margin: 0"
            >
              <el-table
                :data="optionForm.optionTableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                v-loading="optionImageLoading"
              >
                <el-table-column type="index" width="75px">
                  <template slot="header">
                    选项排序<span class="red">*</span>
                  </template>
                </el-table-column>
                <el-table-column>
                  <template slot="header">
                    选项内容<span class="red">*</span>
                  </template>
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'optionTableData.' + scope.$index + '.content'"
                      :rules="optionFormRules.content"
                      :style="
                        scope.row.is_tips == 2
                          ? 'width: 48%;display: inline-block;'
                          : 'width: 100%'
                      "
                    >
                      <el-input
                        placeholder="请输入选项内容"
                        v-model="scope.row.content"
                        maxlength="100"
                      >
                      </el-input>
                    </el-form-item>
                    <el-form-item
                      style="width: 48%; display: inline-block; float: right"
                      v-show="scope.row.is_tips == 2"
                    >
                      <el-input
                        placeholder="请输入填空提示内容（选填）"
                        v-model="scope.row.tips_content"
                        maxlength="100"
                      >
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="address"
                  label="选项图片（选填）"
                  width="180px"
                >
                  <template slot-scope="scope">
                    <el-col
                      :span="12"
                      :class="[scope.row.image ? 'hasImage' : '']"
                    >
                      <el-upload
                        class="list-uploader"
                        :action="ossUrl"
                        :headers="ossHeader"
                        :show-file-list="false"
                        :on-success="uploadSuccessOption.bind(null, scope.row)"
                        :on-error="uploadErrorOption"
                        :before-upload="beforeUploadOption"
                      >
                        <el-link :underline="false" type="primary">{{
                          scope.row.image ? '重新上传' : '上传图片'
                        }}</el-link>
                      </el-upload>
                    </el-col>
                    <el-col
                      :span="12"
                      :class="[scope.row.image ? 'hasImage' : '']"
                    >
                      <el-image
                        style="width: 50px; height: 50px"
                        class="hasImage"
                        :src="scope.row.image"
                        :preview-src-list="[scope.row.image]"
                        v-show="scope.row.image != ''"
                      >
                      </el-image>
                    </el-col>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="130px">
                  <template slot-scope="scope">
                    <el-link
                      :underline="false"
                      type="primary"
                      @click="moveUp(scope.row)"
                      v-show="scope.row.sort != 0"
                      >上移</el-link
                    >
                    {{ scope.row.sort != 0 ? '&nbsp;' : '' }}
                    <el-link
                      :underline="false"
                      type="primary"
                      @click="moveDown(scope.row)"
                      v-show="
                        scope.row.sort != optionForm.optionTableData.length - 1
                      "
                      >下移</el-link
                    >
                    {{
                      scope.row.sort != optionForm.optionTableData.length - 1
                        ? '&nbsp;'
                        : ''
                    }}
                    <el-link
                      :underline="false"
                      type="primary"
                      @click="deleteOption(scope.row)"
                      >删除</el-link
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-row>
        </el-form-item>
        <el-form-item
          label="选项显示方式"
          prop="display_way"
          v-show="questionAddForm.type != 3"
          :rules="
            questionAddForm.type != 3
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-select
            v-model="questionAddForm.display_way"
            placeholder="请选择选项显示方式"
            filterable
            clearable
          >
            <el-option
              key="1"
              label="图片"
              :value="typeof questionAddForm.display_way == 'string' ? '1' : 1"
            >
            </el-option>
            <el-option
              key="2"
              label="圆形"
              :value="typeof questionAddForm.display_way == 'string' ? '2' : 2"
            >
            </el-option>
            <el-option
              key="3"
              label="圆角矩形"
              :value="typeof questionAddForm.display_way == 'string' ? '3' : 3"
            >
            </el-option>
          </el-select>
          <div class="form-item-tips">
            <span style="vertical-align: middle"
              >若选项不使用图片则根据需求选择显示方式</span
            >
            <el-link
              type="primary"
              :underline="false"
              @click="displayModeDescribe"
              >【查看选项样式】</el-link
            >
          </div>
        </el-form-item>
        <el-form-item
          label="内容对齐方式"
          prop="align_way"
          v-show="questionAddForm.type != 3"
          :rules="
            questionAddForm.type != 3
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-select
            v-model="questionAddForm.align_way"
            placeholder="请选择内容对齐方式"
            filterable
            clearable
          >
            <el-option
              key="1"
              label="不展示内容"
              :value="typeof questionAddForm.align_way == 'string' ? '1' : 1"
            >
            </el-option>
            <el-option
              key="2"
              label="内部居中"
              :value="typeof questionAddForm.align_way == 'string' ? '2' : 2"
            >
            </el-option>
            <el-option
              key="3"
              label="底部居中"
              :value="typeof questionAddForm.align_way == 'string' ? '3' : 3"
            >
            </el-option>
          </el-select>
          <div class="form-item-tips">
            <span style="vertical-align: middle"
              >根据选项显示方式选择内容对齐方式</span
            >
            <el-link
              type="primary"
              :underline="false"
              @click="alignmentDescribe"
              >【查看内容对齐方式样式】</el-link
            >
          </div>
        </el-form-item>
        <el-form-item
          label="选项布局"
          prop="layout"
          v-show="questionAddForm.type != 3"
          :rules="
            questionAddForm.type != 3
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-select
            v-model="questionAddForm.layout"
            placeholder="请选择选项布局"
            filterable
            clearable
          >
            <el-option
              key="1"
              label="单列"
              :value="typeof questionAddForm.layout == 'string' ? '1' : 1"
            >
            </el-option>
            <el-option
              key="2"
              label="2列"
              :value="typeof questionAddForm.layout == 'string' ? '2' : 2"
            >
            </el-option>
            <el-option
              key="3"
              label="3列"
              :value="typeof questionAddForm.layout == 'string' ? '3' : 3"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="可选范围"
          v-show="questionAddForm.type == 2"
          required
        >
          <el-col :span="12">
            <el-form-item
              prop="range_min"
              :rules="
                questionAddForm.type == 2
                  ? [{ required: true, message: '请选择', trigger: 'change' }]
                  : []
              "
            >
              <el-select
                v-model="questionAddForm.range_min"
                placeholder="最少选几项"
                filterable
                clearable
              >
                <el-option
                  label="不限"
                  :value="
                    typeof questionAddForm.range_max == 'string' ? '0' : 0
                  "
                >
                </el-option>
                <el-option
                  v-for="(item, index) in questionAddForm.option_data"
                  :key="index"
                  :label="index + 1"
                  :value="index + 1"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="range_max"
              :rules="
                questionAddForm.type == 2
                  ? [{ required: true, message: '请选择', trigger: 'change' }]
                  : []
              "
            >
              <el-select
                v-model="questionAddForm.range_max"
                placeholder="最多选几项"
                filterable
                clearable
              >
                <el-option
                  label="不限"
                  :value="
                    typeof questionAddForm.range_max == 'string' ? '0' : 0
                  "
                >
                </el-option>
                <el-option
                  v-for="(item, index) in questionAddForm.option_data"
                  :key="index"
                  :label="index + 1"
                  :value="index + 1"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="是否显示题干说明" prop="show_stem">
          <el-radio
            v-model="questionAddForm.show_stem"
            :label="typeof questionAddForm.show_stem == 'string' ? '0' : 0"
            >否</el-radio
          >
          <el-radio
            v-model="questionAddForm.show_stem"
            :label="typeof questionAddForm.show_stem == 'string' ? '1' : 1"
            >是</el-radio
          >
        </el-form-item>
        <div v-show="questionAddForm.show_stem == 1">
          <el-form-item
            label="题干标题"
            prop="stem_title"
            :rules="
              questionAddForm.show_stem == 1
                ? [{ required: true, message: '请输入', trigger: 'blur' }]
                : []
            "
          >
            <el-input
              v-model="questionAddForm.stem_title"
              placeholder="请输入题干标题，例如：犬的体型特征"
              maxlength="100"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="题干描述"
            prop="stem_describe"
            :rules="
              questionAddForm.show_stem == 1
                ? [{ required: true, message: '请输入', trigger: 'blur' }]
                : []
            "
          >
            <el-row v-loading="quillUpdateImg">
              <quill-editor
                v-model="questionAddForm.stem_describe"
                ref="myQuillEditorQ"
                :options="editorOption"
                @blur="onEditorBlur($event)"
                @focus="onEditorFocus($event)"
                @ready="onEditorReady($event)"
                @change="onEditorChange($event)"
                class="editor space-ql-editor"
              ></quill-editor>
            </el-row>
          </el-form-item>
        </div>
        <el-form-item label="是否更新宠物信息" prop="update_pets">
          <el-radio
            v-model="questionAddForm.update_pets"
            :label="typeof questionAddForm.update_pets == 'string' ? '0' : 0"
            >否</el-radio
          >
          <el-radio
            v-model="questionAddForm.update_pets"
            :label="typeof questionAddForm.update_pets == 'string' ? '1' : 1"
            >是</el-radio
          >
          <div class="form-item-tips">
            当客户回答问题内容和原来的宠物信息不一致，若需要更新原来的宠物信息则勾选“是”
          </div>
        </el-form-item>
        <el-form-item
          label="更新信息类型"
          prop="update_pets_type"
          v-show="questionAddForm.update_pets == 1"
          :rules="
            questionAddForm.update_pets == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-select
            v-model="questionAddForm.update_pets_type"
            placeholder="请选择信息类型"
            filterable
            clearable
          >
            <el-option
              key="6"
              label="宠物昵称"
              :value="
                typeof questionAddForm.update_pets_type == 'string' ? '6' : 6
              "
            >
            </el-option>
            <el-option
              key="1"
              label="宠物类型"
              :value="
                typeof questionAddForm.update_pets_type == 'string' ? '1' : 1
              "
            >
            </el-option>
            <el-option
              key="2"
              label="宠物品种"
              :value="
                typeof questionAddForm.update_pets_type == 'string' ? '2' : 2
              "
            >
            </el-option>
            <el-option
              key="3"
              label="宠物性别"
              :value="
                typeof questionAddForm.update_pets_type == 'string' ? '3' : 3
              "
            >
            </el-option>
            <el-option
              key="4"
              label="宠物体重"
              :value="
                typeof questionAddForm.update_pets_type == 'string' ? '4' : 4
              "
            >
            </el-option>
            <el-option
              key="5"
              label="宠物年龄"
              :value="
                typeof questionAddForm.update_pets_type == 'string' ? '5' : 5
              "
            >
            </el-option>
            <el-option
              key="7"
              label="宠物是否绝育"
              :value="
                typeof questionAddForm.update_pets_type == 'string' ? '7' : 7
              "
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 图片上传组件辅助-->
        <el-upload
          class="avatar-uploader-ques"
          :action="ossUrl"
          :headers="ossHeader"
          :show-file-list="false"
          :on-success="uploadSuccessQ"
          :on-error="uploadErrorQ"
          :before-upload="beforeUploadQ"
        >
        </el-upload>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button class="theme-background-color" @click="saveQuestionInfo"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import '@/assets/css/quill.css'
import toolbarOptions from '../../assets/js/quillToolbar.js'
export default {
  props: {
    questionAddDialogVisible: {
      type: Boolean,
      default: function () {
        return {}
      }
    },
    questionnaireId: {
      type: String,
      default: function () {
        return {}
      }
    },
    questionInfoNow: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      visible: this.questionAddDialogVisible,
      questionAddForm: {
        id: '',
        question_class: '',
        type: '1',
        title: '',
        option_data: [],
        show_stem: '0',
        update_pets: '0',
        stem_title: '',
        stem_describe: '',
        update_pets_type: '',
        layout: '',
        range_min: '',
        range_max: '',
        tips_content: '',
        content_limit: '',
        word_limit: 'false',
        word_limit_num: '',
        display_way: '',
        align_way: '',
        sort: ''
      },
      questionAddFormRules: {
        question_class: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        title: [{ required: true, message: '请输入', trigger: 'blur' }],
        show_stem: [{ required: true, message: '请选择', trigger: 'change' }],
        update_pets: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      optionForm: {
        optionTableData: []
      },
      optionFormRules: {
        content: [{ required: true, message: '请输入', trigger: 'blur' }]
        // tips_content: [{ required: true, message: '请输入', trigger: 'blur' }]
      },

      //富文本编辑器配置
      editorOption: {
        //主题
        theme: 'snow',
        placeholder: '请输入题干内容描述',
        //  富文本编辑器配置
        modules: {
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          },
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.avatar-uploader-ques input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画
      ossUrl: this.GLOBAL.ossUrl,
      ossHeader: this.GLOBAL.ossHeader,
      optionImageLoading: false, // 选项内容上传图片的loading动画
      imgUrl: '',

      classData: [] //问题分类
    }
  },
  created() {
    this.getClassData()
  },
  methods: {
    async getClassData() {
      const { data: res } = await this.$http.post(
        '/admin/question_manage/getQuestionClass'
      )
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.classData = res.data
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.$refs.questionAddFormRef.resetFields()
          this.$emit('update:questionAddDialogVisible', false)
          done()
        })
        .catch((_) => {})
    },
    tableRowClassName({ row, rowIndex }) {
      //   把每一行的索引放进row
      row.sort = rowIndex
    },
    closeDialog() {
      this.$emit('update:questionAddDialogVisible', false)
    },
    addSingleOption() {
      if (!this.validateField('optionFormRef')) {
        return
      }
      this.optionForm.optionTableData.push({
        id: '',
        is_tips: '1',
        content: '',
        tips_content: '',
        image: ''
      })
    },
    addPackOption() {
      if (!this.validateField('optionFormRef')) {
        return
      }
      this.optionForm.optionTableData.push({
        id: '',
        is_tips: '2',
        content: '',
        tips_content: '',
        image: ''
      })
    },
    deleteOption(row) {
      this.optionForm.optionTableData.splice(row.sort, 1)
    },
    moveUp(row) {
      console.log(row.sort)
      let upData = this.optionForm.optionTableData[row.sort - 1]
      this.optionForm.optionTableData.splice(row.sort - 1, 1)
      this.optionForm.optionTableData.splice(row.sort, 0, upData)
    },
    moveDown(row) {
      let downData = this.optionForm.optionTableData[row.sort + 1]
      this.optionForm.optionTableData.splice(row.sort + 1, 1)
      this.optionForm.optionTableData.splice(row.sort, 0, downData)
    },
    saveQuestionInfo() {
      this.$refs.questionAddFormRef.validate(async (valid) => {
        if (!valid) return

        if (!this.validateField('optionFormRef')) {
          return
        }
        // 如果选项显示方式是图片，单选题和多选题的选项必须上传图片
        console.log(this.questionAddForm.option_data)
        const optionData = this.questionAddForm.option_data
        if (
          this.questionAddForm.type != 3 &&
          this.questionAddForm.display_way == 1
        ) {
          for (let i = 0; i < optionData.length; i++) {
            if (optionData[i].image == '') {
              return this.$message.error(
                '第' + (i + 1) + '行的选项图片不能为空'
              )
            }
          }
        }
        if (this.questionnaireId != 0) {
          console.log(this.questionnaireId)
          const confirmResult = await this.$confirm(
            '是否确认保存？保存后该问卷将被添加到数据库中，如不需要需删除并保存。',
            '提示',
            {
              confirmButtonText: '确定保存',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).catch((err) => err)
          if (confirmResult !== 'confirm') {
            return this.$message.info('已取消操作')
          }
          const { data: res } = await this.$http.post(
            '/admin/question_manage/addQuestion',
            {
              id: this.questionnaireId,
              question_data: [this.questionAddForm]
            }
          )
          // 返回结果
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.questionAddForm.id = res.data
        }
        console.log(this.questionAddForm)
        this.$emit('showQuestionInfo', this.questionAddForm)
        this.visible = false
        this.$emit('update:questionAddDialogVisible', false)
      })
    },
    //失去焦点事件
    onEditorBlur(quill) {
      // console.log('editor blur!', quill)
    },
    //获得焦点事件
    onEditorFocus(quill) {
      // console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      // console.log('editor ready!', quill)
    },
    //内容改变事件
    onEditorChange({ quill, html, text }) {
      console.log('editor change!', quill, html, text)
      this.questionAddForm.stem_describe = html
    },
    // 上传图片前
    beforeUploadQ(file) {
      // 显示loading动画
      this.quillUpdateImg = true
    },
    // 上传图片成功
    uploadSuccessQ(res, file) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      console.log(this.$refs)
      let quill = this.$refs.myQuillEditorQ.quill
      // 如果上传成功
      if (Number.parseInt(res.code) === 10001) {
        console.log(res.data.url)
        // 获取光标所在位置
        let length = quill.getSelection().index
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, 'image', res.data.url)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },
    // 上传图片失败
    uploadErrorQ(res, file) {
      // loading动画消失
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    // 对部分表单字段进行校验
    validateField(form, index = '') {
      let result = true
      for (let item of this.$refs[form].fields) {
        // if (item.prop.split('.')[1] == index) {
        this.$refs[form].validateField(item.prop, (error) => {
          // console.log(error)
          if (error != '') {
            result = false
          }
        })
        // }
        if (!result) break
      }
      return result
    },
    // // 对部分表单字段进行重置
    // resetField(form, index) {
    //   this.$refs[form].fields.forEach((item) => {
    //     if (item.prop.split('.')[1] == index) {
    //       item.resetField()
    //     }
    //   })
    // },
    uploadPicture(row) {
      this.imgUrl = ''
      // 触发input框选择图片文件
      document.querySelector('.list-uploader input').click()
      row.image = this.imgUrl
      console.log(this.imgUrl, row.image)
    },
    // 上传图片前
    beforeUploadOption(file) {
      // 显示loading动画
      this.optionImageLoading = true
      const isJPG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG) {
        this.$message.error('上传图片只能是 PNG 格式!')
        this.optionImageLoading = false
      } else if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!')
        this.optionImageLoading = false
      }
      return isJPG && isLt2M
    },
    // 上传图片成功
    uploadSuccessOption(row, res, file) {
      // res为图片服务器返回的数据
      // 如果上传成功
      console.log(this.$refs)
      if (Number.parseInt(res.code) === 10001) {
        console.log(res.data.url)
        row.image = res.data.url
      } else {
        this.$message.error(res.message)
      }
      // loading动画消失
      this.optionImageLoading = false
    },
    // 上传图片失败
    uploadErrorOption(res, file) {
      // loading动画消失
      this.optionImageLoading = false
      this.$message.error('上传图片失败')
    },
    displayModeDescribe() {
      let explain =
        '<div><div style="display: inline-block;vertical-align: middle;">1. 圆形样式：</div><div style="width: 100px;height: 100px;background-color: #e2e2e2;border-radius: 50%;display: inline-block;vertical-align: middle;"></div></div><div style="margin-top: 20px"><div style="display: inline-block;vertical-align: middle;">2. 圆角矩形样式：</div><div style="width: 130px;height: 35px;border-radius: 6px;border-width: 1px;border-style: solid;border-color: rgb(170, 170, 170);display: inline-block;vertical-align: middle;"></div></div><div style="margin-top: 20px">说明：若选择图片，则根据上传的图片展示</div>'
      this.$alert(explain, ' 查看选项样式', {
        showConfirmButton: false,
        dangerouslyUseHTMLString: true,
        callback: (action) => {}
      })
    },
    alignmentDescribe() {
      let explain =
        '<div>以圆形样式为例，以下为内容对齐方式的展示：</div><div style="margin-top: 20px"><div style="width: 100px;height: 100px;background-color: #e2e2e2;border-radius: 50%;display: inline-block;vertical-align: middle;"><div style="text-align: center;margin-top: 100px;">底部居中</div></div><div style="width: 100px;height: 100px;background-color: #e2e2e2;border-radius: 50%;display: inline-block;vertical-align: middle;margin-left: 80px;line-height: 100px;text-align: center;">内部居中</div></div><div style="margin-top: 40px">说明：内容显示方式的“不展示”常用于图片选项，只会显示图片不会显示选项内容</div>'
      this.$alert(explain, ' 查看内容对齐方式样式', {
        showConfirmButton: false,
        dangerouslyUseHTMLString: true,
        callback: (action) => {}
      })
    }
  },
  watch: {
    questionAddDialogVisible() {
      this.visible = this.questionAddDialogVisible
      if (!this.visible) {
        this.$refs.questionAddFormRef.resetFields()
        this.optionForm.optionTableData = []
      } else {
        console.log(this.$refs)
        if (JSON.stringify(this.questionInfoNow) != '{}') {
          console.log(this.questionInfoNow)
          this.questionAddForm = this.questionInfoNow
          this.optionForm.optionTableData = this.questionInfoNow.option_data
        }
      }
      console.log(this.questionInfoNow)
    },
    'optionForm.optionTableData': {
      handler: function (val, oldval) {
        this.questionAddForm.option_data = val
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-table th.el-table__cell {
  background-color: #f2f2f2 !important;
  color: #333333 !important;
}
.red {
  color: #d9001b;
}
.el-form {
  margin: 0px 15px;
  .el-select {
    width: 100%;
  }
}
/deep/.el-table .el-table__cell {
  padding: 5px 0;
  .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
}

/deep/.editor {
  line-height: normal !important;
  height: 200px;
}
/deep/.ql-container {
  height: 134px;
}
.dialog-footer {
  .el-button {
    width: 160px;
  }
}
.hasImage {
  vertical-align: middle;
  line-height: 50px;
}
.form-item-tips {
  color: #7f7f7f;
}
/deep/.el-dialog__footer {
  text-align: center;
  .el-button {
    width: 160px;
  }
}
</style>
